home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 2002 November / SGI Freeware 2002 November - Disc 3.iso / dist / fw_mysql.idb / usr / freeware / bin / mysqlhotcopy.z / mysqlhotcopy
Encoding:
Text File  |  2002-10-07  |  27.3 KB  |  1,004 lines

  1. #!/usr/sbin/perl -w
  2.  
  3. use strict;
  4. use Getopt::Long;
  5. use Data::Dumper;
  6. use File::Basename;
  7. use File::Path;
  8. use DBI;
  9. use Sys::Hostname;
  10.  
  11. =head1 NAME
  12.  
  13. mysqlhotcopy - fast on-line hot-backup utility for local MySQL databases and tables
  14.  
  15. =head1 SYNOPSIS
  16.  
  17.   mysqlhotcopy db_name
  18.  
  19.   mysqlhotcopy --suffix=_copy db_name_1 ... db_name_n
  20.  
  21.   mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
  22.  
  23.   mysqlhotcopy db_name./regex/
  24.  
  25.   mysqlhotcopy db_name./^\(foo\|bar\)/
  26.  
  27.   mysqlhotcopy db_name./~regex/
  28.  
  29.   mysqlhotcopy db_name_1./regex_1/ db_name_1./regex_2/ ... db_name_n./regex_n/ /path/to/new_directory
  30.  
  31.   mysqlhotcopy --method='scp -Bq -i /usr/home/foo/.ssh/identity' --user=root --password=secretpassword \
  32.          db_1./^nice_table/ user@some.system.dom:~/path/to/new_directory
  33.  
  34. WARNING: THIS PROGRAM IS STILL IN BETA. Comments/patches welcome.
  35.  
  36. =cut
  37.  
  38. # Documentation continued at end of file
  39.  
  40. my $VERSION = "1.16";
  41.  
  42. my $opt_tmpdir = $ENV{TMPDIR} || "/tmp";
  43.  
  44. my $OPTIONS = <<"_OPTIONS";
  45.  
  46. $0 Ver $VERSION
  47.  
  48. Usage: $0 db_name[./table_regex/] [new_db_name | directory]
  49.  
  50.   -?, --help           display this helpscreen and exit
  51.   -u, --user=#         user for database login if not current user
  52.   -p, --password=#     password to use when connecting to server
  53.   -h, --host=#           Hostname for local server when connecting over TCP/IP
  54.   -P, --port=#         port to use when connecting to local server with TCP/IP
  55.   -S, --socket=#       socket to use when connecting to local server
  56.  
  57.   --allowold           don\'t abort if target already exists (rename it _old)
  58.   --keepold            don\'t delete previous (now renamed) target when done
  59.   --noindices          don\'t include full index files in copy
  60.   --method=#           method for copy (only "cp" currently supported)
  61.  
  62.   -q, --quiet          be silent except for errors
  63.   --debug              enable debug
  64.   -n, --dryrun         report actions without doing them
  65.  
  66.   --regexp=#           copy all databases with names matching regexp
  67.   --suffix=#           suffix for names of copied databases
  68.   --checkpoint=#       insert checkpoint entry into specified db.table
  69.   --flushlog           flush logs once all tables are locked 
  70.   --resetmaster        reset the binlog once all tables are locked
  71.   --resetslave         reset the master.info once all tables are locked
  72.   --tmpdir=#           temporary directory (instead of $opt_tmpdir)
  73.   --record_log_pos=#   record slave and master status in specified db.table
  74.  
  75.   Try \'perldoc $0 for more complete documentation\'
  76. _OPTIONS
  77.  
  78. sub usage {
  79.     die @_, $OPTIONS;
  80. }
  81.  
  82. my %opt = (
  83.     user    => scalar getpwuid($>),
  84.     noindices    => 0,
  85.     allowold    => 0,    # for safety
  86.     keepold    => 0,
  87.     method    => "cp",
  88.     flushlog    => 0,
  89. );
  90. Getopt::Long::Configure(qw(no_ignore_case)); # disambuguate -p and -P
  91. GetOptions( \%opt,
  92.     "help",
  93.     "user|u=s",
  94.     "password|p=s",
  95.     "port|P=s",
  96.     "socket|S=s",
  97.     "allowold!",
  98.     "keepold!",
  99.     "noindices!",
  100.     "method=s",
  101.     "debug",
  102.     "quiet|q",
  103.     "mv!",
  104.     "regexp=s",
  105.     "suffix=s",
  106.     "checkpoint=s",
  107.     "record_log_pos=s",
  108.     "flushlog",
  109.     "resetmaster",
  110.     "resetslave",
  111.     "tmpdir|t=s",
  112.     "dryrun|n",
  113. ) or usage("Invalid option");
  114.  
  115. # @db_desc
  116. # ==========
  117. # a list of hash-refs containing:
  118. #
  119. #   'src'     - name of the db to copy
  120. #   't_regex' - regex describing tables in src
  121. #   'target'  - destination directory of the copy
  122. #   'tables'  - array-ref to list of tables in the db
  123. #   'files'   - array-ref to list of files to be copied
  124. #               (RAID files look like 'nn/name.MYD')
  125. #   'index'   - array-ref to list of indexes to be copied
  126. #
  127.  
  128. my @db_desc = ();
  129. my $tgt_name = undef;
  130.  
  131. usage("") if ($opt{help});
  132.  
  133. if ( $opt{regexp} || $opt{suffix} || @ARGV > 2 ) {
  134.     $tgt_name   = pop @ARGV unless ( exists $opt{suffix} );
  135.     @db_desc = map { s{^([^\.]+)\./(.+)/$}{$1}; { 'src' => $_, 't_regex' => ( $2 ? $2 : '.*' ) } } @ARGV;
  136. }
  137. else {
  138.     usage("Database name to hotcopy not specified") unless ( @ARGV );
  139.  
  140.     $ARGV[0] =~ s{^([^\.]+)\./(.+)/$}{$1};
  141.     @db_desc = ( { 'src' => $ARGV[0], 't_regex' => ( $2 ? $2 : '.*' ) } );
  142.  
  143.     if ( @ARGV == 2 ) {
  144.     $tgt_name   = $ARGV[1];
  145.     }
  146.     else {
  147.     $opt{suffix} = "_copy";
  148.     }
  149. }
  150.  
  151. my %mysqld_vars;
  152. my $start_time = time;
  153. $opt_tmpdir= $opt{tmpdir} if $opt{tmpdir};
  154. $0 = $1 if $0 =~ m:/([^/]+)$:;
  155. $opt{quiet} = 0 if $opt{debug};
  156. $opt{allowold} = 1 if $opt{keepold};
  157.  
  158. # --- connect to the database ---
  159. my $dsn;
  160. $dsn  = ";host=" . (defined($opt{host}) ? $opt{host} : "localhost");
  161. $dsn .= ";port=$opt{port}" if $opt{port};
  162. $dsn .= ";mysql_socket=$opt{socket}" if $opt{socket};
  163.  
  164. my $dbh = DBI->connect("dbi:mysql:$dsn;mysql_read_default_group=mysqlhotcopy",
  165.                         $opt{user}, $opt{password},
  166. {
  167.     RaiseError => 1,
  168.     PrintError => 0,
  169.     AutoCommit => 1,
  170. });
  171.  
  172. # --- check that checkpoint table exists if specified ---
  173. if ( $opt{checkpoint} ) {
  174.     eval { $dbh->do( qq{ select time_stamp, src, dest, msg 
  175.              from $opt{checkpoint} where 1 != 1} );
  176.        };
  177.  
  178.     die "Error accessing Checkpoint table ($opt{checkpoint}): $@"
  179.       if ( $@ );
  180. }
  181.  
  182. # --- check that log_pos table exists if specified ---
  183. if ( $opt{record_log_pos} ) {
  184.     eval { $dbh->do( qq{ select host, time_stamp, log_file, log_pos, master_host, master_log_file, master_log_pos
  185.              from $opt{record_log_pos} where 1 != 1} );
  186.        };
  187.  
  188.     die "Error accessing log_pos table ($opt{record_log_pos}): $@"
  189.       if ( $@ );
  190. }
  191.  
  192. # --- get variables from database ---
  193. my $sth_vars = $dbh->prepare("show variables like 'datadir'");
  194. $sth_vars->execute;
  195. while ( my ($var,$value) = $sth_vars->fetchrow_array ) {
  196.     $mysqld_vars{ $var } = $value;
  197. }
  198. my $datadir = $mysqld_vars{'datadir'}
  199.     || die "datadir not in mysqld variables";
  200. $datadir =~ s:/$::;
  201.  
  202.  
  203. # --- get target path ---
  204. my ($tgt_dirname, $to_other_database);
  205. $to_other_database=0;
  206. if (defined($tgt_name) && $tgt_name =~ m:^\w+$: && @db_desc <= 1)
  207. {
  208.     $tgt_dirname = "$datadir/$tgt_name";
  209.     $to_other_database=1;
  210. }
  211. elsif (defined($tgt_name) && ($tgt_name =~ m:/: || $tgt_name eq '.')) {
  212.     $tgt_dirname = $tgt_name;
  213. }
  214. elsif ( $opt{suffix} ) {
  215.     print "Using copy suffix '$opt{suffix}'\n" unless $opt{quiet};
  216. }
  217. else
  218. {
  219.   $tgt_name="" if (!defined($tgt_name));
  220.   die "Target '$tgt_name' doesn't look like a database name or directory path.\n";
  221. }
  222.  
  223. # --- resolve database names from regexp ---
  224. if ( defined $opt{regexp} ) {
  225.     my $sth_dbs = $dbh->prepare("show databases");
  226.     $sth_dbs->execute;
  227.     while ( my ($db_name) = $sth_dbs->fetchrow_array ) {
  228.     push @db_desc, { 'src' => $db_name } if ( $db_name =~ m/$opt{regexp}/o );
  229.     }
  230. }
  231.  
  232. # --- get list of tables to hotcopy ---
  233.  
  234. my $hc_locks = "";
  235. my $hc_tables = "";
  236. my $num_tables = 0;
  237. my $num_files = 0;
  238.  
  239. foreach my $rdb ( @db_desc ) {
  240.     my $db = $rdb->{src};
  241.     my @dbh_tables = get_list_of_tables( $db );
  242.  
  243.     ## generate regex for tables/files
  244.     my $t_regex;
  245.     my $negated;
  246.     if ($rdb->{t_regex}) {
  247.         $t_regex = $rdb->{t_regex};        ## assign temporary regex
  248.         $negated = $t_regex =~ tr/~//d;    ## remove and count
  249.                                            ## negation operator: we
  250.                                            ## don't allow ~ in table
  251.                                            ## names
  252.  
  253.         $t_regex = qr/$t_regex/;           ## make regex string from
  254.                                            ## user regex
  255.  
  256.         ## filter (out) tables specified in t_regex
  257.         print "Filtering tables with '$t_regex'\n" if $opt{debug};
  258.         @dbh_tables = ( $negated 
  259.                         ? grep { $_ !~ $t_regex } @dbh_tables
  260.                         : grep { $_ =~ $t_regex } @dbh_tables );
  261.     }
  262.  
  263.     ## get list of files to copy
  264.     my $db_dir = "$datadir/$db";
  265.     opendir(DBDIR, $db_dir ) 
  266.       or die "Cannot open dir '$db_dir': $!";
  267.  
  268.     my %db_files;
  269.     my @raid_dir = ();
  270.  
  271.     while ( defined( my $name = readdir DBDIR ) ) {
  272.     if ( $name =~ /^\d\d$/ && -d "$db_dir/$name" ) {
  273.         push @raid_dir, $name;
  274.     }
  275.     else {
  276.         $db_files{$name} = $1 if ( $name =~ /(.+)\.\w+$/ );
  277.         }
  278.     }
  279.     closedir( DBDIR );
  280.  
  281.     scan_raid_dir( \%db_files, $db_dir, @raid_dir );
  282.  
  283.     unless( keys %db_files ) {
  284.     warn "'$db' is an empty database\n";
  285.     }
  286.  
  287.     ## filter (out) files specified in t_regex
  288.     my @db_files;
  289.     if ($rdb->{t_regex}) {
  290.         @db_files = ($negated
  291.                      ? grep { $db_files{$_} !~ $t_regex } keys %db_files
  292.                      : grep { $db_files{$_} =~ $t_regex } keys %db_files );
  293.     }
  294.     else {
  295.         @db_files = keys %db_files;
  296.     }
  297.  
  298.     @db_files = sort @db_files;
  299.  
  300.     my @index_files=();
  301.  
  302.     ## remove indices unless we're told to keep them
  303.     if ($opt{noindices}) {
  304.         @index_files= grep { /\.(ISM|MYI)$/ } @db_files;
  305.     @db_files = grep { not /\.(ISM|MYI)$/ } @db_files;
  306.     }
  307.  
  308.     $rdb->{files}  = [ @db_files ];
  309.     $rdb->{index}  = [ @index_files ];
  310.     my @hc_tables = map { "`$db`.`$_`" } @dbh_tables;
  311.     $rdb->{tables} = [ @hc_tables ];
  312.  
  313.     $rdb->{raid_dirs} = [ get_raid_dirs( $rdb->{files} ) ];
  314.  
  315.     $hc_locks .= ", "  if ( length $hc_locks && @hc_tables );
  316.     $hc_locks .= join ", ", map { "$_ READ" } @hc_tables;
  317.     $hc_tables .= ", "  if ( length $hc_tables && @hc_tables );
  318.     $hc_tables .= join ", ", @hc_tables;
  319.  
  320.     $num_tables += scalar @hc_tables;
  321.     $num_files  += scalar @{$rdb->{files}};
  322. }
  323.  
  324. # --- resolve targets for copies ---
  325.  
  326. if (defined($tgt_name) && length $tgt_name ) {
  327.     # explicit destination directory specified
  328.  
  329.     # GNU `cp -r` error message
  330.     die "copying multiple databases, but last argument ($tgt_dirname) is not a directory\n"
  331.       if ( @db_desc > 1 && !(-e $tgt_dirname && -d $tgt_dirname ) );
  332.  
  333.     if ($to_other_database)
  334.     {
  335.       foreach my $rdb ( @db_desc ) {
  336.     $rdb->{target} = "$tgt_dirname";
  337.       }
  338.     }
  339.     elsif ($opt{method} =~ /^scp\b/) 
  340.     {   # we have to trust scp to hit the target
  341.     foreach my $rdb ( @db_desc ) {
  342.         $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  343.     }
  344.     }
  345.     else
  346.     {
  347.       die "Last argument ($tgt_dirname) is not a directory\n"
  348.     if (!(-e $tgt_dirname && -d $tgt_dirname ) );
  349.       foreach my $rdb ( @db_desc ) {
  350.     $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  351.       }
  352.     }
  353.   }
  354. else {
  355.   die "Error: expected \$opt{suffix} to exist" unless ( exists $opt{suffix} );
  356.  
  357.   foreach my $rdb ( @db_desc ) {
  358.     $rdb->{target} = "$datadir/$rdb->{src}$opt{suffix}";
  359.   }
  360. }
  361.  
  362. print Dumper( \@db_desc ) if ( $opt{debug} );
  363.  
  364. # --- bail out if all specified databases are empty ---
  365.  
  366. die "No tables to hot-copy" unless ( length $hc_locks );
  367.  
  368. # --- create target directories if we are using 'cp' ---
  369.  
  370. my @existing = ();
  371.  
  372. if ($opt{method} =~ /^cp\b/)
  373. {
  374.   foreach my $rdb ( @db_desc ) {
  375.     push @existing, $rdb->{target} if ( -d  $rdb->{target} );
  376.   }
  377.  
  378.   if ( @existing && !$opt{allowold} )
  379.   {
  380.     $dbh->disconnect();
  381.     die "Can't hotcopy to '", join( "','", @existing ), "' because directory\nalready exist and the --allowold option was not given.\n"
  382.   }
  383. }
  384.  
  385. retire_directory( @existing ) if ( @existing );
  386.  
  387. foreach my $rdb ( @db_desc ) {
  388.     foreach my $td ( '', @{$rdb->{raid_dirs}} ) {
  389.  
  390.     my $tgt_dirpath = "$rdb->{target}/$td";
  391.     if ( $opt{dryrun} ) {
  392.         print "mkdir $tgt_dirpath, 0750\n";
  393.     }
  394.     elsif ($opt{method} =~ /^scp\b/) {
  395.         ## assume it's there?
  396.         ## ...
  397.     }
  398.     else {
  399.         mkdir($tgt_dirpath, 0750)
  400.         or die "Can't create '$tgt_dirpath': $!\n";
  401.     }
  402.     }
  403. }
  404.  
  405. ##############################
  406. # --- PERFORM THE HOT-COPY ---
  407. #
  408. # Note that we try to keep the time between the LOCK and the UNLOCK
  409. # as short as possible, and only start when we know that we should
  410. # be able to complete without error.
  411.  
  412. # read lock all the tables we'll be copying
  413. # in order to get a consistent snapshot of the database
  414.  
  415. if ( $opt{checkpoint} || $opt{record_log_pos} ) {
  416.   # convert existing READ lock on checkpoint and/or log_pos table into WRITE lock
  417.   foreach my $table ( grep { defined } ( $opt{checkpoint}, $opt{record_log_pos} ) ) {
  418.     $hc_locks .= ", $table WRITE" 
  419.     unless ( $hc_locks =~ s/$table\s+READ/$table WRITE/ );
  420.   }
  421. }
  422.  
  423. my $hc_started = time;    # count from time lock is granted
  424.  
  425. if ( $opt{dryrun} ) {
  426.     print "LOCK TABLES $hc_locks\n";
  427.     print "FLUSH TABLES /*!32323 $hc_tables */\n";
  428.     print "FLUSH LOGS\n" if ( $opt{flushlog} );
  429.     print "RESET MASTER\n" if ( $opt{resetmaster} );
  430.     print "RESET SLAVE\n" if ( $opt{resetslave} );
  431. }
  432. else {
  433.     my $start = time;
  434.     $dbh->do("LOCK TABLES $hc_locks");
  435.     printf "Locked $num_tables tables in %d seconds.\n", time-$start unless $opt{quiet};
  436.     $hc_started = time;    # count from time lock is granted
  437.  
  438.     # flush tables to make on-disk copy uptodate
  439.     $start = time;
  440.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  441.     printf "Flushed tables ($hc_tables) in %d seconds.\n", time-$start unless $opt{quiet};
  442.     $dbh->do( "FLUSH LOGS" ) if ( $opt{flushlog} );
  443.     $dbh->do( "RESET MASTER" ) if ( $opt{resetmaster} );
  444.     $dbh->do( "RESET SLAVE" ) if ( $opt{resetslave} );
  445.  
  446.     if ( $opt{record_log_pos} ) {
  447.     record_log_pos( $dbh, $opt{record_log_pos} );
  448.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  449.     }
  450. }
  451.  
  452. my @failed = ();
  453.  
  454. foreach my $rdb ( @db_desc )
  455. {
  456.   my @files = map { "$datadir/$rdb->{src}/$_" } @{$rdb->{files}};
  457.   next unless @files;
  458.   
  459.   eval { copy_files($opt{method}, \@files, $rdb->{target}, $rdb->{raid_dirs} ); };
  460.   push @failed, "$rdb->{src} -> $rdb->{target} failed: $@"
  461.     if ( $@ );
  462.   
  463.   @files = @{$rdb->{index}};
  464.   if ($rdb->{index})
  465.   {
  466.     copy_index($opt{method}, \@files,
  467.            "$datadir/$rdb->{src}", $rdb->{target} );
  468.   }
  469.   
  470.   if ( $opt{checkpoint} ) {
  471.     my $msg = ( $@ ) ? "Failed: $@" : "Succeeded";
  472.     
  473.     eval {
  474.       $dbh->do( qq{ insert into $opt{checkpoint} (src, dest, msg) 
  475.               VALUES ( '$rdb->{src}', '$rdb->{target}', '$msg' )
  476.             } ); 
  477.     };
  478.     
  479.     if ( $@ ) {
  480.       warn "Failed to update checkpoint table: $@\n";
  481.     }
  482.   }
  483. }
  484.  
  485. if ( $opt{dryrun} ) {
  486.     print "UNLOCK TABLES\n";
  487.     if ( @existing && !$opt{keepold} ) {
  488.     my @oldies = map { $_ . '_old' } @existing;
  489.     print "rm -rf @oldies\n" 
  490.     }
  491.     $dbh->disconnect();
  492.     exit(0);
  493. }
  494. else {
  495.     $dbh->do("UNLOCK TABLES");
  496. }
  497.  
  498. my $hc_dur = time - $hc_started;
  499. printf "Unlocked tables.\n" unless $opt{quiet};
  500.  
  501. #
  502. # --- HOT-COPY COMPLETE ---
  503. ###########################
  504.  
  505. $dbh->disconnect;
  506.  
  507. if ( @failed ) {
  508.     # hotcopy failed - cleanup
  509.     # delete any @targets 
  510.     # rename _old copy back to original
  511.  
  512.     my @targets = ();
  513.     foreach my $rdb ( @db_desc ) {
  514.         push @targets, $rdb->{target} if ( -d  $rdb->{target} );
  515.     }
  516.     print "Deleting @targets \n" if $opt{debug};
  517.  
  518.     print "Deleting @targets \n" if $opt{debug};
  519.     rmtree([@targets]);
  520.     if (@existing) {
  521.     print "Restoring @existing from back-up\n" if $opt{debug};
  522.         foreach my $dir ( @existing ) {
  523.         rename("${dir}_old", $dir )
  524.           or warn "Can't rename ${dir}_old to $dir: $!\n";
  525.     }
  526.     }
  527.  
  528.     die join( "\n", @failed );
  529. }
  530. else {
  531.     # hotcopy worked
  532.     # delete _old unless $opt{keepold}
  533.  
  534.     if ( @existing && !$opt{keepold} ) {
  535.     my @oldies = map { $_ . '_old' } @existing;
  536.     print "Deleting previous copy in @oldies\n" if $opt{debug};
  537.     rmtree([@oldies]);
  538.     }
  539.  
  540.     printf "$0 copied %d tables (%d files) in %d second%s (%d seconds overall).\n",
  541.         $num_tables, $num_files,
  542.         $hc_dur, ($hc_dur==1)?"":"s", time - $start_time
  543.     unless $opt{quiet};
  544. }
  545.  
  546. exit 0;
  547.  
  548.  
  549. # ---
  550.  
  551. sub copy_files {
  552.     my ($method, $files, $target, $raid_dirs) = @_;
  553.     my @cmd;
  554.     print "Copying ".@$files." files...\n" unless $opt{quiet};
  555.  
  556.     if ($method =~ /^s?cp\b/) { # cp or scp with optional flags
  557.     my @cp = ($method);
  558.     # add option to preserve mod time etc of copied files
  559.     # not critical, but nice to have
  560.     push @cp, "-p" if $^O =~ m/^(solaris|linux|freebsd)$/;
  561.  
  562.     # add recursive option for scp
  563.     push @cp, "-r" if $^O =~ /m^(solaris|linux|freebsd)$/ && $method =~ /^scp\b/;
  564.  
  565.     my @non_raid = map { "'$_'" } grep { ! m:/\d{2}/[^/]+$: } @$files;
  566.  
  567.     # add files to copy and the destination directory
  568. +     safe_system( @cp, @non_raid, "'$target'" );
  569.     
  570.     foreach my $rd ( @$raid_dirs ) {
  571.         my @raid = map { "'$_'" } grep { m:$rd/: } @$files;
  572.         safe_system( @cp, @raid, "'$target'/$rd" ) if ( @raid );
  573.     }
  574.     }
  575.     else
  576.     {
  577.     die "Can't use unsupported method '$method'\n";
  578.     }
  579. }
  580.  
  581. #
  582. # Copy only the header of the index file
  583. #
  584.  
  585. sub copy_index
  586. {
  587.   my ($method, $files, $source, $target) = @_;
  588.   my $tmpfile="$opt_tmpdir/mysqlhotcopy$$";
  589.   
  590.   print "Copying indices for ".@$files." files...\n" unless $opt{quiet};  
  591.   foreach my $file (@$files)
  592.   {
  593.     my $from="$source/$file";
  594.     my $to="$target/$file";
  595.     my $buff;
  596.     open(INPUT, "<$from") || die "Can't open file $from: $!\n";
  597.     my $length=read INPUT, $buff, 2048;
  598.     die "Can't read index header from $from\n" if ($length < 1024);
  599.     close INPUT;
  600.     
  601.     if ( $opt{dryrun} )
  602.     {
  603.       print "$opt{method}-header $from $to\n";
  604.     }
  605.     elsif ($opt{method} eq 'cp')
  606.     {
  607.       open(OUTPUT,">$to")   || die "Can\'t create file $to: $!\n";
  608.       if (syswrite(OUTPUT,$buff) != length($buff))
  609.       {
  610.     die "Error when writing data to $to: $!\n";
  611.       }
  612.       close OUTPUT       || die "Error on close of $to: $!\n";
  613.     }
  614.     elsif ($opt{method} eq 'scp')
  615.     {
  616.       my $tmp=$tmpfile;
  617.       open(OUTPUT,">$tmp") || die "Can\'t create file $tmp: $!\n";
  618.       if (syswrite(OUTPUT,$buff) != length($buff))
  619.       {
  620.     die "Error when writing data to $tmp: $!\n";
  621.       }
  622.       close OUTPUT         || die "Error on close of $tmp: $!\n";
  623.       safe_system("scp $tmp $to");
  624.     }
  625.     else
  626.     {
  627.       die "Can't use unsupported method '$opt{method}'\n";
  628.     }
  629.   }
  630.   unlink "$tmpfile" if  ($opt{method} eq 'scp');
  631. }
  632.  
  633.  
  634. sub safe_system
  635. {
  636.   my @cmd= @_;
  637.  
  638.   if ( $opt{dryrun} )
  639.   {
  640.     print "@cmd\n";
  641.     return;
  642.   }
  643.  
  644.   ## for some reason system fails but backticks works ok for scp...
  645.   print "Executing '@cmd'\n" if $opt{debug};
  646.   my $cp_status = system "@cmd > /dev/null";
  647.   if ($cp_status != 0) {
  648.     warn "Burp ('scuse me). Trying backtick execution...\n" if $opt{debug}; #'
  649.     ## try something else
  650.     `@cmd` && die "Error: @cmd failed ($cp_status) while copying files.\n";
  651.   }
  652. }
  653.  
  654. sub retire_directory {
  655.     my ( @dir ) = @_;
  656.  
  657.     foreach my $dir ( @dir ) {
  658.     my $tgt_oldpath = $dir . '_old';
  659.     if ( $opt{dryrun} ) {
  660.         print "rmtree $tgt_oldpath\n" if ( -d $tgt_oldpath );
  661.         print "rename $dir, $tgt_oldpath\n";
  662.         next;
  663.     }
  664.  
  665.     if ( -d $tgt_oldpath ) {
  666.         print "Deleting previous 'old' hotcopy directory ('$tgt_oldpath')\n" unless $opt{quiet};
  667.         rmtree([$tgt_oldpath])
  668.     }
  669.     rename($dir, $tgt_oldpath)
  670.       or die "Can't rename $dir=>$tgt_oldpath: $!\n";
  671.     print "Existing hotcopy directory renamed to '$tgt_oldpath'\n" unless $opt{quiet};
  672.     }
  673. }
  674.  
  675. sub record_log_pos {
  676.     my ( $dbh, $table_name ) = @_;
  677.  
  678.     eval {
  679.     my ($file,$position) = get_row( $dbh, "show master status" );
  680.     die "master status is undefined" if !defined $file || !defined $position;
  681.     
  682.     my ($master_host, undef, undef, undef, $log_file, $log_pos ) 
  683.         = get_row( $dbh, "show slave status" );
  684.     
  685.     my $hostname = hostname();
  686.     
  687.     $dbh->do( qq{ replace into $table_name 
  688.               set host=?, log_file=?, log_pos=?, 
  689.                           master_host=?, master_log_file=?, master_log_pos=? }, 
  690.           undef, 
  691.           $hostname, $file, $position, 
  692.           $master_host, $log_file, $log_pos  );
  693.     
  694.     };
  695.     
  696.     if ( $@ ) {
  697.     warn "Failed to store master position: $@\n";
  698.     }
  699. }
  700.  
  701. sub get_row {
  702.   my ( $dbh, $sql ) = @_;
  703.  
  704.   my $sth = $dbh->prepare($sql);
  705.   $sth->execute;
  706.   return $sth->fetchrow_array();
  707. }
  708.  
  709. sub scan_raid_dir {
  710.     my ( $r_db_files, $data_dir, @raid_dir ) = @_;
  711.  
  712.     local(*RAID_DIR);
  713.     
  714.     foreach my $rd ( @raid_dir ) {
  715.  
  716.     opendir(RAID_DIR, "$data_dir/$rd" ) 
  717.         or die "Cannot open dir '$data_dir/$rd': $!";
  718.  
  719.     while ( defined( my $name = readdir RAID_DIR ) ) {
  720.         $r_db_files->{"$rd/$name"} = $1 if ( $name =~ /(.+)\.\w+$/ );
  721.     }
  722.     closedir( RAID_DIR );
  723.     }
  724. }
  725.  
  726. sub get_raid_dirs {
  727.     my ( $r_files ) = @_;
  728.  
  729.     my %dirs = ();
  730.     foreach my $f ( @$r_files ) {
  731.     if ( $f =~ m:^(\d\d)/: ) {
  732.         $dirs{$1} = 1;
  733.     }
  734.     }
  735.     return sort keys %dirs;
  736. }
  737.  
  738. sub get_list_of_tables {
  739.     my ( $db ) = @_;
  740.  
  741.     # "use database" cannot cope with database names containing spaces
  742.     # so create a new connection 
  743.  
  744.     my $dbh = DBI->connect("dbi:mysql:${db}${dsn};mysql_read_default_group=mysqlhotcopy",
  745.                 $opt{user}, $opt{password},
  746.     {
  747.     RaiseError => 1,
  748.     PrintError => 0,
  749.     AutoCommit => 1,
  750.     });
  751.  
  752.     my @dbh_tables = eval { $dbh->tables() };
  753.     $dbh->disconnect();
  754.     return @dbh_tables;
  755. }
  756.  
  757. __END__
  758.  
  759. =head1 DESCRIPTION
  760.  
  761. mysqlhotcopy is designed to make stable copies of live MySQL databases.
  762.  
  763. Here "live" means that the database server is running and the database
  764. may be in active use. And "stable" means that the copy will not have
  765. any corruptions that could occur if the table files were simply copied
  766. without first being locked and flushed from within the server.
  767.  
  768. =head1 OPTIONS
  769.  
  770. =over 4
  771.  
  772. =item --checkpoint checkpoint-table
  773.  
  774. As each database is copied, an entry is written to the specified
  775. checkpoint-table.  This has the happy side-effect of updating the
  776. MySQL update-log (if it is switched on) giving a good indication of
  777. where roll-forward should begin for backup+rollforward schemes.
  778.  
  779. The name of the checkpoint table should be supplied in database.table format.
  780. The checkpoint-table must contain at least the following fields:
  781.  
  782. =over 4
  783.  
  784.   time_stamp timestamp not null
  785.   src varchar(32)
  786.   dest varchar(60)
  787.   msg varchar(255)
  788.  
  789. =back
  790.  
  791. =item --record_log_pos log-pos-table
  792.  
  793. Just before the database files are copied, update the record in the
  794. log-pos-table from the values returned from "show master status" and
  795. "show slave status". The master status values are stored in the
  796. log_file and log_pos columns, and establish the position in the binary
  797. logs that any slaves of this host should adopt if initialised from
  798. this dump.  The slave status values are stored in master_host,
  799. master_log_file, and master_log_pos, and these are useful if the host
  800. performing the dump is a slave and other sibling slaves are to be
  801. initialised from this dump.
  802.  
  803. The name of the log-pos table should be supplied in database.table format.
  804. A sample log-pos table definition:
  805.  
  806. =over 4
  807.  
  808. CREATE TABLE log_pos (
  809.   host            varchar(60) NOT null,
  810.   time_stamp      timestamp(14) NOT NULL,
  811.   log_file        varchar(32) default NULL,
  812.   log_pos         int(11)     default NULL,
  813.   master_host     varchar(60) NULL,
  814.   master_log_file varchar(32) NULL,
  815.   master_log_pos  int NULL,
  816.  
  817.   PRIMARY KEY  (host) 
  818. );
  819.  
  820. =back
  821.  
  822.  
  823. =item --suffix suffix
  824.  
  825. Each database is copied back into the originating datadir under
  826. a new name. The new name is the original name with the suffix
  827. appended. 
  828.  
  829. If only a single db_name is supplied and the --suffix flag is not
  830. supplied, then "--suffix=_copy" is assumed.
  831.  
  832. =item --allowold
  833.  
  834. Move any existing version of the destination to a backup directory for
  835. the duration of the copy. If the copy successfully completes, the backup 
  836. directory is deleted - unless the --keepold flag is set.  If the copy fails,
  837. the backup directory is restored.
  838.  
  839. The backup directory name is the original name with "_old" appended.
  840. Any existing versions of the backup directory are deleted.
  841.  
  842. =item --keepold
  843.  
  844. Behaves as for the --allowold, with the additional feature 
  845. of keeping the backup directory after the copy successfully completes.
  846.  
  847. =item --flushlog
  848.  
  849. Rotate the log files by executing "FLUSH LOGS" after all tables are
  850. locked, and before they are copied.
  851.  
  852. =item --resetmaster
  853.  
  854. Reset the bin-log by executing "RESET MASTER" after all tables are
  855. locked, and before they are copied. Usefull if you are recovering a
  856. slave in a replication setup.
  857.  
  858. =item --resetslave
  859.  
  860. Reset the master.info by executing "RESET SLAVE" after all tables are
  861. locked, and before they are copied. Usefull if you are recovering a
  862. server in a mutual replication setup.
  863.  
  864. =item --regexp pattern
  865.  
  866. Copy all databases with names matching the pattern
  867.  
  868. =item db_name./pattern/
  869.  
  870. Copy only tables matching pattern. Shell metacharacters ( (, ), |, !,
  871. etc.) have to be escaped (e.g. \). For example, to select all tables
  872. in database db1 whose names begin with 'foo' or 'bar':
  873.  
  874.     mysqlhotcopy --indices --method=cp db1./^\(foo\|bar\)/
  875.  
  876. =item db_name./~pattern/
  877.  
  878. Copy only tables not matching pattern. For example, to copy tables
  879. that do not begin with foo nor bar:
  880.  
  881.     mysqlhotcopy --indices --method=cp db1./~^\(foo\|bar\)/
  882.  
  883. =item -?, --help
  884.  
  885. Display helpscreen and exit
  886.  
  887. =item -u, --user=#         
  888.  
  889. user for database login if not current user
  890.  
  891. =item -p, --password=#     
  892.  
  893. password to use when connecting to server
  894.  
  895. =item -h, -h, --host=#
  896.  
  897. Hostname for local server when connecting over TCP/IP.  By specifying this
  898. different from 'localhost' will trigger mysqlhotcopy to use TCP/IP connection.
  899.  
  900. =item -P, --port=#         
  901.  
  902. port to use when connecting to MySQL server with TCP/IP.  This is only used
  903. when using the --host option.
  904.  
  905. =item -S, --socket=#         
  906.  
  907. UNIX domain socket to use when connecting to local server
  908.  
  909. =item  --noindices          
  910.  
  911. Don\'t include index files in copy. Only up to the first 2048 bytes
  912. are copied;  You can restore the indexes with isamchk -r or myisamchk -r
  913. on the backup.
  914.  
  915. =item  --method=#           
  916.  
  917. method for copy (only "cp" currently supported). Alpha support for
  918. "scp" was added in November 2000. Your experience with the scp method
  919. will vary with your ability to understand how scp works. 'man scp'
  920. and 'man ssh' are your friends.
  921.  
  922. The destination directory _must exist_ on the target machine using the
  923. scp method. --keepold and --allowold are meeningless with scp.
  924. Liberal use of the --debug option will help you figure out what\'s
  925. really going on when you do an scp.
  926.  
  927. Note that using scp will lock your tables for a _long_ time unless
  928. your network connection is _fast_. If this is unacceptable to you,
  929. use the 'cp' method to copy the tables to some temporary area and then
  930. scp or rsync the files at your leisure.
  931.  
  932. =item -q, --quiet              
  933.  
  934. be silent except for errors
  935.  
  936. =item  --debug
  937.  
  938. Debug messages are displayed 
  939.  
  940. =item -n, --dryrun
  941.  
  942. Display commands without actually doing them
  943.  
  944. =back
  945.  
  946. =head1 WARRANTY
  947.  
  948. This software is free and comes without warranty of any kind. You
  949. should never trust backup software without studying the code yourself.
  950. Study the code inside this script and only rely on it if I<you> believe
  951. that it does the right thing for you.
  952.  
  953. Patches adding bug fixes, documentation and new features are welcome.
  954. Please send these to internals@lists.mysql.com.
  955.  
  956. =head1 TO DO
  957.  
  958. Extend the individual table copy to allow multiple subsets of tables
  959. to be specified on the command line:
  960.  
  961.   mysqlhotcopy db newdb  t1 t2 /^foo_/ : t3 /^bar_/ : +
  962.  
  963. where ":" delimits the subsets, the /^foo_/ indicates all tables
  964. with names begining with "foo_" and the "+" indicates all tables
  965. not copied by the previous subsets.
  966.  
  967. newdb is either another not existing database or a full path to a directory
  968. where we can create a directory 'db'
  969.  
  970. Add option to lock each table in turn for people who don\'t need
  971. cross-table integrity.
  972.  
  973. Add option to FLUSH STATUS just before UNLOCK TABLES.
  974.  
  975. Add support for other copy methods (eg tar to single file?).
  976.  
  977. Add support for forthcoming MySQL ``RAID'' table subdirectory layouts.
  978.  
  979. =head1 AUTHOR
  980.  
  981. Tim Bunce
  982.  
  983. Martin Waite - added checkpoint, flushlog, regexp and dryrun options
  984.                Fixed cleanup of targets when hotcopy fails. 
  985.            Added --record_log_pos.
  986.                RAID tables are now copied (don't know if this works over scp).
  987.  
  988. Ralph Corderoy - added synonyms for commands
  989.  
  990. Scott Wiersdorf - added table regex and scp support
  991.  
  992. Monty - working --noindex (copy only first 2048 bytes of index file)
  993.         Fixes for --method=scp
  994.  
  995. Ask Bjoern Hansen - Cleanup code to fix a few bugs and enable -w again.
  996.  
  997. Emil S. Hansen - Added resetslave and resetmaster.
  998.  
  999. Jeremy D. Zawodny - Removed depricated DBI calls.  Fixed bug which
  1000. resulted in nothing being copied when a regexp was specified but no
  1001. database name(s).
  1002.  
  1003. Martin Waite - Fix to handle database name that contains space.
  1004.